<template>
  <div class="header">
    <div class="header-content">
      <div class="header-left">
        <div class="avatar">
          <img :src="userStore.personalDetailInfo?.avatar" alt="头像" />
          <div class="edit-avatar">
            <el-upload
              ref="uploadRef"
              :action="uploadAction"
              :on-success="handleCoverSuccess"
              :before-upload="beforeCoverUpload"
              :on-error="handleCoverError"
              :show-file-list="false"
              :headers="headers"
              method="post"
              accept=".jpg, .png, .jpeg"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <template #trigger>
                <div class="edit-avatar-icon">
                  <el-icon :size="18"><Edit /></el-icon> 
                </div>
              </template>
            </el-upload>
          </div>
        </div>
        <!-- <div class="avatar" v-else></div> -->
        <div class="header-info">
          <div class="header-name">
            <span v-if="!isEditing">{{ userStore.personalDetailInfo?.username || '用户名称' }}</span>
            <el-input 
              v-else 
              v-model="editedName" 
              @keyup.enter="saveName"
              @blur="saveName"
              ref="inputRef"
              size="small"
            ></el-input>
            <div class="edit-name" @click="editName" v-if="!isEditing"><el-icon :size="14"><Edit /></el-icon></div>
          </div>
          <div class="header-desc">加入云帆美研 努力学习的第 <span>{{ daysSinceRegistration + 1 }}</span> 天~</div>
        </div>
      </div>
      <div class="header-right">
        <div class="headerAccount">
          <div class="headerAccountNum">{{ userStore.personalDetailInfo?.question_num || 0 }}</div>
          <div class="headerAccountText">累计刷题</div>
        </div>
        <div class="headerIntegral">
          <div class="headerIntegralNum">{{ userStore.personalDetailInfo?.point_num || 0 }}</div>
          <div class="headerIntegralText">积分</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useUserStore } from "@/stores/User";
import { ElMessage } from 'element-plus';
import { computed, ref, nextTick } from 'vue';
import dayjs from "dayjs";
import avatar from "@/static/image.png";
import { editAvatar, updateUsername } from "@/service/personalCenter";

const uploadRef = ref(null);
const uploadAction = ref('https://admin.testace.cn/fenglingClient/client/uploads');
const headers = ref({});

const form = ref({
    cover: ''
});
const loading = ref(false);
const userStore = useUserStore();
console.log(userStore.personalDetailInfo, 'userStore.personalDetailInfo')

const token = userStore.userInfo?.token;

const daysSinceRegistration = computed(() => {
  if (!userStore.personalDetailInfo?.create_time) {
    return 0;
  }
  // Parse create_time from the API
  const createTime = new Date(userStore.personalDetailInfo.create_time * 1000);
  // Get current time
  const currentTime = new Date();
  
  // Calculate the difference in milliseconds
  const timeDifference = currentTime.getTime() - createTime.getTime();
  
  // Convert milliseconds to days (1000ms * 60s * 60min * 24h)
  const daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
  
  return daysDifference > 0 ? daysDifference : 1; // At least one day
});

const isEditing = ref(false);
const editedName = ref('');
const inputRef = ref(null);

// 上传成功回调
const handleCoverSuccess = (response, uploadFile) => {
    // 实际项目中，这里应该使用response中的图片URL
    console.log(response, 'response')
    // const imageUrl = URL.createObjectURL(uploadFile.raw);
    const imageUrl = response.data.url;
    userStore.personalDetailInfo.avatar = imageUrl;
    editAvatar({avatar: imageUrl}).then(res => {
      if(res.code === '000000'){
        ElMessage.success('头像修改成功！');
      }
    })
};

const handleCoverError = (error, file) => {
    ElMessage.success('头像修改失败');
    loading.value = false;
}

const handleExceed = (files, fileList) => {
    uploadRef.value.clearFiles();
    const file = files[0];
    file.uid = genFileId()
    uploadRef.value.handleStart(file);
    uploadRef.value.submit();
}

// 上传前校验
const beforeCoverUpload = (file) => {
    headers.value.token = token;
    const isImage = file.type.startsWith('image/');
    // const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
        ElMessage.error('上传封面图只能是图片格式!');
    }
    loading.value = true;
    // if (!isLt2M) {
    //     ElMessage.error('上传封面图大小不能超过 2MB!');
    // }
    // return isImage && isLt2M;
    return isImage;
};

const editName = () => {
  isEditing.value = true;
  editedName.value = userStore.personalDetailInfo?.username || '';
  nextTick(() => {
    inputRef.value.focus();
  });
}

const saveName = async () => {
  if (!editedName.value.trim()) {
    ElMessage.warning('用户名不能为空');
    return;
  }
  
  try {
    const res = await updateUsername({ username: editedName.value.trim() });
    if (res.code === '000000') {
      userStore.personalDetailInfo.username = editedName.value.trim();
      ElMessage.success('用户名修改成功');
    } else {
      ElMessage.error(res.msg || '修改失败');
    }
  } catch (error) {
    ElMessage.error('修改失败，请稍后重试');
  } finally {
    isEditing.value = false;
  }
}
</script>

<style lang="scss" scoped>
.header {
  background-color: #ffffff;
  border-radius: 5px;
  margin-top: 15px;

  &-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 20px;
    .header-left {
      display: flex;
      align-items: center;
      padding: 8px;
      .avatar {
        width: 40px;
        height: 40px;
        background-color: #ccc;
        border-radius: 50%;
        background-size: cover;
        background-position: center;
        position: relative;
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
        }
        .edit-avatar {
          position: absolute;
          bottom: 0;
          background-color: rgba(0, 0, 0, 0.5);
          z-index: 1;
          width: 100%;
          height: 100%;
          border-radius: 50%;
          opacity: 0;
          transition: opacity 0.2s ease;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .edit-avatar-icon {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            margin-top: 5px;
          }
          
          &:hover {
            opacity: 0.8;
          }
        }
      }
      .header-info {
        margin-left: 10px;
        .header-name {
          width: fit-content;
          font-size: 14px;
          font-weight: bold;
          cursor: pointer;
          position: relative;
          display: flex;
          align-items: center;
          .edit-name {
            margin-left: 5px;
            cursor: pointer;
            color: var(--main-color);
            align-items: center;
            justify-content: center;
            display: flex;
            opacity: 0;
            transition: opacity 0.2s ease;
          }
          &:hover {
            .edit-name {
              opacity: 1;
            }
          }
        }
        .header-desc {
          font-size: var(--default12px);
          color: var(--otherFontColor);
          margin-top: 4px;
          > span {
            color: var(--main-color);
          }
        }
      }
    }
    .header-right {
      display: flex;
      align-items: center;
      .headerAccount {
        .headerAccountNum {
          font-weight: bold;
        }
        .headerAccountText {
          font-size: var(--default12px);
          margin-top: 4px;
          color: var(--otherFontColor);
        }
      }
      .headerIntegral {
        margin-left: 30px;

        .headerIntegralNum {
          font-weight: bold;
        }
        .headerIntegralText {
          font-size: var(--default12px);
          margin-top: 4px;
          color: var(--otherFontColor);
          text-align: center;
        }
      }
    }
  }
}
</style>
